package com.leadcloud.nim.jsbridge;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.TextView;

import com.leadcloud.nim.R;
import com.leadcloud.nim.config.preference.Preferences;
import com.netease.nim.uikit.common.MyConst;
import com.netease.nim.uikit.common.activity.UI;
import com.netease.nim.uikit.common.util.log.LogUtil;
import com.netease.nimlib.jsbridge.core.NIMJsBridge;
import com.netease.nimlib.jsbridge.interfaces.IJavaReplyToJsImageInfo;
import com.netease.nimlib.jsbridge.util.WebViewConfig;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.uinfo.UserService;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;

import java.util.Map;

/**
 *
 */

public class AddInfoActivity extends UI {


    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.js_bridge_activity);
        initWebView();
        initData();
    }
    @Override
    public boolean isTransStatusBar() {
        return true;
    }
    @Override
    protected void onDestroy() {
        if (webView != null) {
            webView.destroy();
        }
        super.onDestroy();
    }

    public static final void start(Context context, String accId) {
        Intent intent = new Intent();
        intent.setClass(context, AddInfoActivity.class);
        intent.putExtra("accid",accId);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
        context.startActivity(intent);
    }
    private SwipeRefreshLayout sr_pull_fresh;

    private void initWebView() {
        webView = findView(R.id.webView);

        WebSettings settings = webView.getSettings();
        WebViewConfig.setWebSettings(this, settings, this.getApplicationInfo().dataDir);
        WebViewConfig.removeJavascriptInterfaces(webView);
        WebViewConfig.setWebViewAllowDebug(true);
        WebViewConfig.setAcceptThirdPartyCookies(webView);

        findView(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        sr_pull_fresh = findView(R.id.sr_pull_fresh);
        sr_pull_fresh.setColorSchemeResources(R.color.primary_color);
        sr_pull_fresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if(webView!=null){
                    saveDataByJs();
                    webView.reload();
                }
                sr_pull_fresh.setRefreshing(false);
            }
        });

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            webView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
                @Override
                public void onScrollChange(View view, int i, int i1, int i2, int i3) {
                    if (webView.getScrollY() == 0){
                        sr_pull_fresh.setEnabled(true);
                    }else {
                        sr_pull_fresh.setEnabled(false);
                    }
                }
            });
        }

        //设置响应js 的Alert()函数
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                AlertDialog.Builder b = new AlertDialog.Builder(AddInfoActivity.this);
                b.setTitle("Alert");
                b.setMessage(message);
                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.confirm();
                    }
                });
                b.setCancelable(false);
                b.create().show();
                return true;
            }
            //设置响应js 的Confirm()函数
            @Override
            public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
                AlertDialog.Builder b = new AlertDialog.Builder(AddInfoActivity.this);
                b.setTitle("Confirm");
                b.setMessage(message);
                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.confirm();
                    }
                });
                b.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.cancel();
                    }
                });
                b.create().show();
                return true;
            }
            //设置响应js 的Prompt()函数
            @Override
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, final JsPromptResult result) {
                final View v = View.inflate(AddInfoActivity.this, R.layout.prompt_dialog, null);
                ((TextView) v.findViewById(R.id.prompt_message_text)).setText(message);
                ((EditText) v.findViewById(R.id.prompt_input_field)).setText(defaultValue);
                AlertDialog.Builder b = new AlertDialog.Builder(AddInfoActivity.this);
                b.setTitle("Prompt");
                b.setView(v);
                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String value = ((EditText) v.findViewById(R.id.prompt_input_field)).getText().toString();
                        result.confirm(value);
                    }
                });
                b.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.cancel();
                    }
                });
                b.create().show();
                return true;
            }

        });

        webView.setWebViewClient(new WebViewClient(){
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onPageFinished(WebView view, String url) {



                super.onPageFinished(view, url);
            }
        });
    }

    private void initData() {
        // return CommonCache.getContext().getSharedPreferences("Demo", Context.MODE_PRIVATE);

        //enterpriseId：企业id
        //userId：用户id
        //userName：用户名
        //currentUrl：初次访问网址
        //proj：访客id
        //source：来源（1:访客历史,2:网站留言,3:直接创建,4:聊天）
        //sourceName 表单名（留言表的名字 ps:如果不是从网站留言录入，则不传）
        //sourceId：留言id（那条记录的id ps:如果不是从网站留言录入，则不传）
        NimUserInfo user = NIMClient.getService(UserService.class).getUserInfo(getIntent().getStringExtra("accid"));
        Map<String, Object> extensionMap = user.getExtensionMap();
        String visitorId = (String) extensionMap.get("visitorId");

        StringBuilder sb = new StringBuilder();
        sb.append("?enterpriseId=")
                .append(Preferences.getOrgId())
                .append("&userId=")
                .append(Preferences.getUserId())
                .append("&userName=")
                .append(Preferences.getUserName())
                .append("&proj=")
                .append(visitorId)
                .append("&password=")
                .append(Preferences.getPwd());

        String url = MyConst.ADD_INFO_URL+sb.toString();
        LogUtil.ui(url);
        Preferences.syncCookie(webView,this);
        webView.loadUrl(url);

    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onStop() {
        saveDataByJs();
        super.onStop();
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void saveDataByJs(){
        final int version = Build.VERSION.SDK_INT;
        // 因为该方法在 Android 4.4 版本才可使用，所以使用时需进行版本判断
        if (version < 18) {
            webView.loadUrl("javascript:setlocalStorage()");
        } else {
            webView.evaluateJavascript("javascript:setlocalStorage()", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    //此处为 js 返回的结果
                    //LogUtil.ui("on js:"+value);
                }
            });
        }
    }

}
